/**
 * Copyright (c) 2007 Parity, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *      Joshua Gan
 */

package org.eclipse.higgins.idas.cp.f8;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.eclipse.higgins.idas.api.*;
import org.eclipse.higgins.idas.api.model.IContextModel;
import org.eclipse.higgins.idas.spi.BasicContext;

import org.eclipse.higgins.idas.cp.f8.F8Node;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.facebook.api.FacebookException;
import com.facebook.api.FacebookJsonRestClient;
import com.facebook.api.ProfileField;

import edu.stanford.ejalbert.BrowserLauncher;

/**
 * A
 * <a href="http://www.eclipse.org/higgins/">Higgins</a>
 *  Context for the <a href="http://developer.facebook.com/">F8</a>
 *  Context Provider. 
 *  
 * @author josh.gan@gmail.com
 */

public class F8Context  implements IContext {

    public static final boolean debug = true;
    
    public static final String sessionKey = "sessionKey";
    public static final String sessionSecret = "sessionSecret";

    private IContextId _contextId;
    private boolean _isOpen;
    private String _apiKey;
    private String _apiSecret;
    
    private HashMap<String, INode> _idHashMap;

	private FacebookJsonRestClient client;
    
    
    public F8Context(IContextId contextID, String apiKey, String apiSecret) throws IdASException {
        _contextId = contextID;
        _isOpen = false;
        _apiKey = apiKey;
        _apiSecret = apiSecret;
    }

    
    public String open(Object authentication) throws IdASException, ContextOpenException {

        String api_key = "51d8af6bf3a1bd7773f04df48d284258";
        String secret = "0eac3d4ef9123b5a5e7b9d19f6eb9577";


        client = new FacebookJsonRestClient(api_key, secret);
        

        // uncomment the line below to get details of each request and respnse
        // printed to System.out.
        //  client.setDebug(true);

        String auth;
		try {
			auth = client.auth_createToken();
	        BrowserLauncher browserLauncher = new BrowserLauncher(null);
	        browserLauncher.openURLinBrowser("http://www.facebook.com/login.php?v=1.0" + "&api_key=" + api_key + "&auth_token=" + auth);
//	        System.out.println("hit enter after you have logged into FB");
//	        System.in.read();
	         Thread.sleep(5000); // in ms

	        client.auth_getSession(auth);
	        
	        
	        return addNode(
	        		new F8Node(
	        				this,
	        				new URI("f8://types/people"), 
	        				String.valueOf(client.users_getLoggedInUser())
	        				)
	        		);
	        
	    //    JSONArray userInfos = (JSONArray) client.users_getInfo(new ArrayList<Integer>(client.users_getLoggedInUser()), EnumSet.allOf(ProfileField.class));
//	        
//	        JSONArray d = (JSONArray) client.friends_get();
//	       
//	        //for (int uid : d.)
//	        //	;
//	        Object friendsInfos = client.users_getInfo(d, EnumSet.of(com.facebook.api.ProfileField.BIRTHDAY));
//	        System.out.println(friendsInfos);

		
		} catch (Exception e) {
			throw(new IdASException(e));
		}
    }
    
    
    public INode addNode(INode ds) throws IdASException {
        if ( _idHashMap == null)
            _idHashMap = new HashMap<String, INode>();
        return _idHashMap.put(ds.getNodeID(), ds);
    }
    
    public void close() throws IdASException {
        if (!_isOpen)
            throw new ContextNotOpenException();
        
        if ( _idHashMap != null)
            _idHashMap.clear();
        _idHashMap = null;
        _isOpen = false;
    }

 
    public boolean isOpen(Object identity) throws IdASException {
        return _isOpen;
    }


    public String exportData(String arg0, String arg1)
      throws IdASException {
        throw new NotImplementedException("The Facebook Developers licensing agreement does not allow the \"caching\" of their information.");
    }

    public void importData(String arg0, String arg1)
      throws IdASException {
        throw new NotImplementedException();
    }

    

    /* (non-Javadoc)
     * @see org.eclipse.higgins.idas.api.IContext#getNode(java.lang.String)
     */
    public INode getNode(String cuid) throws IdASException {
        return getNode(cuid, null);
    }

    /* (non-Javadoc)
     * @see org.eclipse.higgins.idas.api.IContext#getNode(java.lang.String, java.lang.Iterable)
     */
    public INode getNode(String cuid, Iterator attrSelectionList)
      throws IdASException {
        if (!_isOpen)
            throw new ContextNotOpenException();

        if ( _idHashMap == null )
            throw new NoSuchNodeException("No such subject: " + cuid);
        
        INode ds = (INode)_idHashMap.get(cuid);
        if ( ds == null)
            throw new NoSuchNodeException("No such subject: " + cuid);

        //
        //  TODO: Currently does not handle attribute selection at all.
        //
        
        return ds;
    }

    /* (non-Javadoc)
     * @see org.eclipse.higgins.idas.api.IContext#getNodes(org.eclipse.higgins.idas.api.IFilter)
     */
    public Iterator getNodes(IFilter filter) throws IdASException {
        return getNodes(filter, null);
    }

    /* (non-Javadoc)
     * @see org.eclipse.higgins.idas.api.IContext#getNodes(org.eclipse.higgins.idas.api.IFilter, java.lang.Iterable)
     */
    public Iterator getNodes(IFilter filter, Iterator attrs) throws IdASException {
        if (!_isOpen)
            throw new ContextNotOpenException();

        throw new NotImplementedException();    
    }

    
    /*
     *  (non-Javadoc)
     * @see org.eclipse.higgins.idas.api.IContext#verifyNodeAttributes(java.lang.String, java.lang.Iterable)
     */
    public boolean verifyNodeAttributes(String arg0, Iterator arg1)
      throws IdASException {
        if (!_isOpen)
            throw new ContextNotOpenException();

        throw new NotImplementedException();
    }

    

    /*
     * (non-Javadoc)
     * @see org.eclipse.higgins.idas.spi.BasicContext#buildRelationship(java.net.URI)
     */
    public IContextRelation buildRelationship(URI type)
      throws IdASException {
        if (!_isOpen)
            throw new ContextNotOpenException();

        throw new NotImplementedException("ToDo for Version 2.0");
    }
    
    /*
     * (non-Javadoc)
     * @see org.eclipse.higgins.idas.spi.BasicContext#addRelationship(org.eclipse.higgins.idas.api.IContextRelation)
     */
    public IContextRelation  addRelationship( URI relationship)
      throws IdASException {
        if (!_isOpen)
            throw new ContextNotOpenException();

        throw new NotImplementedException("ToDo Version 2.0");
    }


	public INode addNode(URI nodeType, String nodeID) throws IdASException,
			InvalidTypeException, InvalidNodeIDException, NodeExistsException {
		// TODO Auto-generated method stub
		return null;
	}

	public void applyUpdates() throws IdASException {
		// TODO Auto-generated method stub
		
	}


	public IAttribute buildAttribute(URI attrID) throws IdASException {
		// TODO Auto-generated method stub
		return null;
	}


	public IFilterAttributeAssertion buildAttributeAssertion()
			throws IdASException {
		// TODO Auto-generated method stub
		return null;
	}


	public IAuthNAttributesMaterials buildAuthNAttributesMaterials()
			throws IdASException {
		// TODO Auto-generated method stub
		return null;
	}


	public IComplexAttrValue buildComplexAttrValue(URI dataType)
			throws IdASException, InvalidTypeException {
		// TODO Auto-generated method stub
		return null;
	}


	public IFilter buildFilter() throws IdASException {
		// TODO Auto-generated method stub
		return null;
	}


	public IFilterMetadataAssertion buildMetadataAssertion()
			throws IdASException {
		// TODO Auto-generated method stub
		return null;
	}


	public IFilterNodeIDAssertion buildNodeIDAssertion() throws IdASException {
		// TODO Auto-generated method stub
		return null;
	}


	public IFilterNodeTypeAssertion buildNodeTypeAssertion()
			throws IdASException {
		// TODO Auto-generated method stub
		return null;
	}


	public ISimpleAttrValue buildSimpleAttrValue(URI dataType, Object value)
			throws IdASException, InvalidTypeException {
		// TODO Auto-generated method stub
		return null;
	}


	public void cancelUpdates() throws IdASException {
		// TODO Auto-generated method stub
		
	}


	public URI getContextID() throws IdASException {
		// TODO Auto-generated method stub
		return null;
	}


	public IContextModel getContextModel() throws IdASException {
		// TODO Auto-generated method stub
		return null;
	}


	public Iterator getRelationships() throws IdASException {
		// TODO Auto-generated method stub
		return null;
	}


	public String getSchema() throws IdASException {
		// TODO Auto-generated method stub
		return null;
	}


	public void setSchema(String schema) throws IdASException {
		// TODO Auto-generated method stub
		
	}

    
}
